package com.zk.fm.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.zk.fm.R;
import com.zk.fm.util.VersionCheckUtil;
import com.zk.fm.util.WebServiceUtil;

public class LaunchActivity extends Activity {
	private TextView currentVersionView;
	private TextView newestVersionView;
	private Button update;
	private Button ignore;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.launch);
		initViews();
		setListener();
		versionCheck();
	}

	private void setListener() {
		update.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(LaunchActivity.this, R.string.baopengForUpdate,
						Toast.LENGTH_SHORT).show();
			}
		});

		ignore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				jumpToLoginPage();

			}
		});
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.obj == null) {
				Toast.makeText(LaunchActivity.this, R.string.checkFail,
						Toast.LENGTH_SHORT).show();
				jumpToLoginPage();
				return;
			}
			currentVersionView.setText(getString(R.string.currentVersion) + ":"
					+ VersionCheckUtil.getAppVersionName(LaunchActivity.this));
			String newestVersion = msg.obj.toString();
			newestVersionView.setText(getString(R.string.newestVersion) + ":"
					+ newestVersion);
			String currentVersion = VersionCheckUtil
					.getAppVersionName(LaunchActivity.this);
			if (newestVersion.compareTo(currentVersion) > 0) {
				System.out.println("has new version");
			} else {
				jumpToLoginPage();
			}

		};
	};

	private void versionCheck() {
		new Thread() {
			@Override
			public void run() {
				try {
					String ret = WebServiceUtil
							.callWebService(
									WebServiceUtil.METHOD_GETNEWESTVERSION,
									null, 10000);
					mHandler.sendMessage(mHandler.obtainMessage(0, ret));
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(0);
				}
			}
		}.start();

	}

	private void initViews() {
		currentVersionView = (TextView) findViewById(R.id.currentVersion);
		newestVersionView = (TextView) findViewById(R.id.newestVersion);
		update = (Button) findViewById(R.id.update);
		ignore = (Button) findViewById(R.id.ignore);
	}

	private void jumpToLoginPage() {
		Intent i = new Intent();
		i.setClass(LaunchActivity.this, LoginActivity.class);
		startActivity(i);
		finish();
	}
}